<template>
  <div>
    <!-- accept="image/*" mutiple="mutiple"   微信和浏览都能调用相机，缺点：可以上传动图 -->
    <input id="upload_file" type="file" style="display: none;" accept="image/*" mutiple="mutiple" name="file"  @change="fileChange($event)"/>
    <div class="image-item space" @click="showActionSheet()">
      <div class="image-up"></div>
    </div>
   
    <div class="upload_head_warp">
      <div class="upload_head_warp_img">
        <div class="upload_head_warp_img_div clear" v-for="(item,index) in imgList" :key="index" @click="fileClick()">
          <!-- <div class="upload_warp_img_div_top">
            <img src="http://114.115.162.39/static/image/x.png" class="upload_warp_img_div_del" @click="fileDel(index)">
          </div> -->
          <label for="" style="width: auto;">{{headerimg}}</label>
          <img :src="item.file.src" style="display: inline-block;">
        </div>
        <div class="upload_head_warp_left clear" id="upload_warp_left" @click="fileClick()" v-if="this.imgList.length < 1" style="margin-left: 0 !important;margin-bottom: 0 !important;">
          <label for="" style="width: auto;">{{headerimg}}</label>
          <img :src="CardLogo" class="imgs"/>
        </div>
      </div>
 
    </div>
  </div>
 
</template>


<script>
import $ from "jquery";
import { checkPlatform } from '@/utils'

// import qs from 'qs';
// import { setLocalStorage, isQuotaExceeded, getLocalStorage } from '../common/js/localstorage.js';
import { post, fetch, patch, put } from '../common/js/http.js';

    export default {
      name: "cameras-and-albums",
      data(){
        return{
          imgList: [],
          datas: new FormData(),
          files:0,
          size:0,
          access_token:'',
          userInfo:'',
          // path:"http://fc.x.e000.com",
        }
      },
      created() {
        let that = this;
        that.userInfo = window.localStorage.getItem('userInfo');
        that.userInfo = JSON.parse(that.userInfo);
      },
      mounted() {
        let that = this;
        that.access_token = window.localStorage.getItem('access_token');
        // var a = Promise.resolve(this.getUserInfo());
        // that.access_token = window.localStorage.getItem('access_token');
        // a.then(function (result) { 
        //     that.userInfo = result;
        //     that.CardLogo = result.userhead;
        //     console.log(result);
        //     console.log(1232131);
        // })

        // if(checkPlatform('android')){
        //   $("input[type='file']").attr("capture","camera");
        // }else if(checkPlatform('ios')){         
        //     $("input[type='file']").removeAttr("capture");
        // }

      },
      methods:{
        //调用相册&相机
        fileClick() {
          $('#upload_file').click();
        },
        //调用手机摄像头并拍照
        getImage() {
          let cmr = plus.camera.getCamera();
          cmr.captureImage(function(p) {
            plus.io.resolveLocalFileSystemURL(p, function(entry) {
              compressImage(entry.toLocalURL(),entry.name);
            }, function(e) {
              plus.nativeUI.toast("读取拍照文件错误：" + e.message);
            });
          }, function(e) {
          }, {
            filter: 'image'
          });
        },
        //从相册选择照片
        galleryImgs() {
          plus.gallery.pick(function(e) {
            let name = e.substr(e.lastIndexOf('/') + 1);
            compressImage(e,name);
          }, function(e) {
          }, {
            filter: "image"
          });
        },
        //点击事件，弹出选择摄像头和相册的选项
        showActionSheet() {
          let bts = [{
            title: "拍照"
          }, {
            title: "从相册选择"
          }];
          plus.nativeUI.actionSheet({
              cancel: "取消",
              buttons: bts
            },
            function(e) {
              if (e.index == 1) {
                this.getImage();
              } else if (e.index == 2) {
                this.galleryImgs();
              }
            }
          );
        },
        fileChange(el) {
          
          this.files=$("#upload_file").get(0).files;
          // console.log(this.files.length);
          for(let i=0;i<this.files.length;i++){
            this.datas.append("file",this.files[i]);
          }

          
          this.show1=false;
          if (!el.target.files[0].size) return;
          this.fileList(el.target);

          el.target.value = ''
        },
        fileList(fileList) {
          let files = fileList.files;
          for (let i = 0; i < files.length; i++) {
            //判断是否为文件夹
            if (files[i].type != '') {
              this.fileAdd(files[i]);
            } else {
              //文件夹处理
              this.folders(fileList.items[i]);
            }

          }
        },
        //文件夹处理
        folders(files) {
          let _this = this;
          //判断是否为原生file
          if (files.kind) {
            files = files.webkitGetAsEntry();
          }
          files.createReader().readEntries(function (file) {
            for (let i = 0; i < file.length; i++) {
              if (file[i].isFile) {
                _this.foldersAdd(file[i]);
              } else {
                _this.folders(file[i]);
              }
            }
          })
        },
        fileAdd(file) {
          this.$openLoading = true;
          //总大小
          
          this.size = this.size + file.size;
          //判断是否为图片文件
          // let formData = new FormData();
          // let config = {
          //   headers:{'Content-Type':'multipart/form-data'}
          // };

          // console.log(file);
          // formData.append('file',file,file.name);
          // formData.append('access_token', getLocalStorage('access_token'));

          // console.log(formData.get('file'));

          if (file.type.indexOf('image') == -1) {
            file.src = 'wenjian.png';
            //把file放到接口里面去，然后再push到数组里面去
            // console.log(file);

            this.imgList.push({
              file
            });

          } else {
            // console.log('走下面了');
            
            let reader = new FileReader();
            
            reader.vue = this;
            reader.readAsDataURL(file);
            reader.onload = function () {
            file.src = this.result;
             

              this.vue.imgList = [];
              this.vue.imgList['access_token'] = window.localStorage.getItem('access_token');
              this.vue.imgList['file'] = file.src;
              
              this.vue.imgList.push({
                file
              });

              // console.log(file);

              // formData.append('access_token', getLocalStorage('access_token'));
              // formData.append('file',file);
              // console.log(formData);
              
              post(this.$path + '/index.php/api/uploadlogo',this.vue.imgList).then((response) => { 
                    
                    if(response.code == 200){
                        this.vue.$closeLoading(); 
                        // location.reload();
                         // this.companylist = response.data;
                         this.vue.$emit("CardLogo",response.data);
                         console.log('进来了',response.data);
                    }else{ 
                         // this.$router.push({path:'/companyBind'});
                    }
              })
            }
          }



        },

        // fileDel(index) {
        //   this.size = this.size - this.imgList[index].file.size;//总大小
        //   this.imgList.splice(index, 1);
        // },
        bytesToSize(bytes) {
          if (bytes === 0){
            return '0 B';
          }
          let k = 1000, // or 1024
            sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
            i = Math.floor(Math.log(bytes) / Math.log(k));
          return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
        },
        dragenter(el) {
          el.stopPropagation();
          el.preventDefault();
        },
        dragover(el) {
          el.stopPropagation();
          el.preventDefault();
        },
        drop(el) {
          el.stopPropagation();
          el.preventDefault();
          this.fileList(el.dataTransfer);
        },
        shows(et,tx){
          this.strut=et;
          this.txt=tx;
        },
        handleClick(){
          this.$store.commit('add')
        },
      },
      props: ['headerimg','CardLogo']
    }
</script>

<style>
.upload_head_warp_left,
.upload_head_warp_img_div {
    width: 100%;
    height: 1rem;
    background-color: #fff;
}
.upload_head_warp_left img,
.upload_head_warp_img_div img {
    width: 0.8rem;
    height: 0.8rem;
    border-radius: 50%;
    margin: 0.1rem;
    margin-right: 0.2rem;
    float: right;
}
.upload_head_warp_left label,
.upload_head_warp_img_div label {
    float: left;
    font-size: 0.28rem;
    color: #333;
    line-height: 1rem;
    padding-left: 0.2rem;
}
</style>